<?php
/**
 * Created by PhpStorm.
 * User: yy
 * Date: 2019/7/9
 * Time: 14:52
 */

namespace app\common\service\SourceAnalysis;

use think\Db;
use think\facade\Config;
use app\common\service\CommonService;
use app\common\service\airquality\AirQualityStationAqiRealtimeDayService;
use app\common\service\EmissionService;
use app\common\service\lastWeek\LastWeekControlAnalysisService;

class SourceAnalysisService
{
    /**
     * 贡献度占比
     * @author yy by 2019/7/9
     * @param array $param
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getContributionRate($param = [])
    {
        $commonService      = new CommonService();
        $newTime            = $commonService->getMongoTime($param);
        $companyIdArr       = $commonService->getCompanyIdArr(0);
        $isIndustryId       = $commonService->getIndustryLimitId();
        $mongodb_huanxin    = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $document           = [
            'aggregate'    => Config::get('contribution_table_name'),
            'pipeline'     => [
                [
                    '$project' => [
                        'predict_time'        => 1,
                        'publish_time'        => 1,
                        'contribution_name'   => 1,
                        'company_id'          => 1,
                        'industry_id'         => 1,
                        'station_id'          => 1,
                        'region_id'           => 1,
                        'contribution_value'  => 1, //贡献度
                        'contribution_degree' => 1, //贡献值
                        'difference'          => ['$eq' => ['$publish_time', '$predict_time']]
                    ],
                ],
                [
                    '$match' => [
                        'difference'        => true,
                        'industry_id'       => ['$in' => $isIndustryId],
                        'company_id'        => ['$in' => $companyIdArr],
                        'region_id'         => (int)$param['region_id'],
                        'station_id'        => (int)$param['station_id'],
                        'contribution_name' => strtoupper($param['pollutant_name']),
                        'predict_time'      => [
                            '$gte' => $newTime['start_time'],
                            '$lte' => $newTime['end_time'],
                        ],
                    ]
                ],
                [
                    '$group' => [
                        '_id'   => ['industry_id' => '$industry_id'],
                        'total' => ['$sum' => '$contribution_degree'] //不同行业下不同企业的时间区间贡献值和sum
                    ]
                ],
            ],
            'allowDiskUse' => true,
        ];
        $command            = new \MongoDB\Driver\Command($document);
        $rows               = $mongodb_huanxin->executeCommand('huanxin', $command)->toArray();
        $contribution_trend = json_decode(json_encode($rows, 320), true);
        $num                = count($contribution_trend[0]['result']); //因为要求计算区间平均减排前贡献度
        $arr                = [];
        $isIndustryIdmysql  = $commonService->getIndustryLimitIdmysql();
        $industry_data      = Db::query("select id,name from basic_industry where type = 1 and delete_time = 0 and id in $isIndustryIdmysql");
        foreach ($industry_data as $k => &$v) {
            $v['value'] = 0;
        }
        if ($num > 0) {
            # 指定污染物的时间区间有效浓度和
            $param['pollutant_name'] = str_replace('.', '', strtolower($param['pollutant_name']));
            $concentration_sum       = $commonService->getConcentration($param);

            # 不同行业不同企业时间区间内的贡献值和
            foreach ($contribution_trend[0]['result'] as $km => $vm) {
                $arr[$vm['_id']['industry_id']] = $vm['total'];
            }
            # 不同行业不同企业时间区间内的贡献度
            foreach ($arr as $kn => &$vn) {
                $vn = $concentration_sum > 0 ? $vn / $concentration_sum : '';
            }
            foreach ($industry_data as $k2 => &$v2) {
                $v2['value'] = $arr[$v2['id']] > 0 ? $commonService->handleMathNum($arr[$v2['id']] * 100) . '%' : $arr[$v2['id']];
            }
        }
        // 非工业贡献度占比
        $no_industry_data = $this->getNoIndustryData($param);
        $result = ['industry'=>$industry_data, 'no_industry'=>$no_industry_data];
        return $result;
    }

    /**
     * 获取非工业贡献度各行业占比
     * @author yy by 2019/7/9
     * @param array $param
     * @return mixed
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getNoIndustryData($param = [])
    {
        $commonService      = new CommonService();
        $newTime            = $commonService->getMongoTime($param);
        $noIndustryId       = $commonService->getNoIndustryLimitId();
        $mongodb_huanxin    = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $document           = [
            'aggregate'    => 'air_quality_pollutant_non_industry_area_forecast_day',
            'pipeline'     => [
                [
                    '$project' => [
                        'predict_time'        => 1,
                        'publish_time'        => 1,
                        'contribution_name'   => 1,
                        'industry_id'         => 1,
                        'station_id'          => 1,
                        'region_id'           => 1,
                        'contribution_value'  => 1, //贡献度
                        'contribution_degree' => 1, //贡献值
                        'difference'          => ['$eq' => ['$publish_time', '$predict_time']]
                    ],
                ],
                [
                    '$match' => [
                        'difference'        => true,
                        'industry_id'       => ['$in' => $noIndustryId],
                        'region_id'         => (int)$param['region_id'],
                        'station_id'        => (int)$param['station_id'],
                        'contribution_name' => strtoupper($param['pollutant_name']),
                        'predict_time'      => [
                            '$gte' => $newTime['start_time'],
                            '$lte' => $newTime['end_time'],
                        ],
                    ]
                ],
                [
                    '$group' => [
                        '_id'   => ['industry_id' => '$industry_id'],
                        'total' => ['$sum' => '$contribution_degree'] //不同行业下不同企业的时间区间贡献值和sum
                    ]
                ],
            ],
            'allowDiskUse' => true,
        ];
        $command            = new \MongoDB\Driver\Command($document);
        $rows               = $mongodb_huanxin->executeCommand('huanxin', $command)->toArray();
        $contribution_trend = json_decode(json_encode($rows, 320), true);
        $num                = count($contribution_trend[0]['result']); //因为要求计算区间平均减排前贡献度
        $arr                = [];
        $no_industry_data   = Db::query('select id,name from basic_industry where type = 2 and delete_time = 0');
        foreach ($no_industry_data as $k3 => &$v3) {
            $v3['value'] = 0;
        }
        if ($num > 0) {
            # 指定污染物的时间区间有效浓度和
            $param['pollutant_name'] = str_replace('.', '', strtolower($param['pollutant_name']));
            $concentration_sum       = $commonService->getConcentration($param);

            # 不同行业不同企业时间区间内的贡献值和
            foreach ($contribution_trend[0]['result'] as $k4 => $v4) {
                $arr[$v4['_id']['industry_id']] = $v4['total'];
            }
            # 不同行业不同企业时间区间内的贡献度
            foreach ($arr as $k5 => &$v5) {
                $v5 = $concentration_sum > 0 ? $v5 / $concentration_sum : '';
            }
            foreach ($no_industry_data as $k6 => &$v6) {
                $v6['value'] = $arr[$v6['id']] > 0 ? $commonService->handleMathNum($arr[$v6['id']] * 100) . '%' : $arr[$v6['id']];
            }
        }
        return $no_industry_data;
    }


}